package com.atguigu.chapter02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * Author: Pepsi
 * Date: 2023/7/24
 * Desc:  flink批处理wordCount
 */
public class Flink01_Batch_WordCount {
    public static void main(String[] args) throws Exception {

        // 1.拿到批处理的执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        // 2. 读文件
        DataSource<String> dataSource = env.readTextFile("input/words.txt");

        dataSource
                // 扁平化，用flatMap
                .flatMap(new FlatMapFunction<String, String>() {

            public void flatMap(String line, Collector<String> out) throws Exception {
                String[] words = line.split(" ");
                for (String word : words) {
                    out.collect(word);
                }
            }
        })
                // 做映射，映射成tuple2元组，注意是对偶元组
                .map(new MapFunction<String, Tuple2<String,Long>>() {

                    public Tuple2 map(String value) throws Exception {
                        return Tuple2.of(value,1L);
                    }
                })

                // 以第一个字段分组
                .groupBy(0)
                .sum(1)
                .print();

    }
}
